#include "esp_log.h"
#include "esp_event.h"
#include "esp_lvgl_port.h"
#include "wireless_debug_ui.h"
#include "main_ui.h"
#include "md_images.h"
#include "md_languages.h"
#include "ui_setting.h"
#include "func_pin_image.h"
#include "work_status_setting.h"
#include "dap_setting.h"
#include "dap_main.h"
#include "dap_usb_handle.h"
#include "mdns_handle.h"
#include "wifi_main.h"
#include "tcp_server.h"

// 声明字体
LV_FONT_DECLARE(myFont);

// 静态变量用于存储UI组件
static lv_obj_t *panel = NULL;
static lv_obj_t *wifi_status_label = NULL;
static lv_obj_t *ip_addr_label = NULL;
static lv_obj_t *connection_hint_label = NULL;
static lv_obj_t *spinner = NULL;
static lv_obj_t *retry_btn = NULL;
// 初始化无线调试UI
static void wireless_debug_init_task(void *pvParameters);
// 退出无线调试界面
void exit_wireless_debug_ui(lv_obj_t *root)
{
    switch_to_main_screen(); // 切换到主界面
    set_work_status(USUALLY_WORK);
    lv_obj_del(root);
    root = NULL;
}

// 手势事件回调
static void event_handler(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);

    if (code == LV_EVENT_GESTURE) {
        lv_indev_t *indev = lv_indev_get_act();
        if (!indev)
            return;

        lv_dir_t dir = lv_indev_get_gesture_dir(indev);
        if (dir == LV_DIR_RIGHT || dir == LV_DIR_TOP) {
            exit_wireless_debug_ui(e->target);
        }
    }
}

// 重试连接回调
static void retry_btn_event_handler(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if (code == LV_EVENT_CLICKED) {
        // 隐藏重试按钮，显示加载动画
        lv_obj_add_flag(retry_btn, LV_OBJ_FLAG_HIDDEN);
        lv_obj_clear_flag(spinner, LV_OBJ_FLAG_HIDDEN);
        lv_obj_set_style_text_color(wifi_status_label, lv_color_hex(0xFFA500), 0); // 橙色-连接中
        lv_label_set_text(wifi_status_label, "连接中...");

        // 重新启动连接任务
        xTaskCreateWithCaps(wireless_debug_init_task, "wireless_init_task", 4 * 1024, NULL, 5, NULL, MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
    }
}

// 更新UI状态
void update_wireless_debug_ui(bool connected, const char *ip_addr)
{
    if (connected) {
        // 连接成功
        lv_obj_add_flag(spinner, LV_OBJ_FLAG_HIDDEN);
        lv_obj_add_flag(retry_btn, LV_OBJ_FLAG_HIDDEN);
        lv_obj_set_style_text_color(wifi_status_label, lv_color_hex(0x00FF00), 0); // 绿色-已连接
        lv_label_set_text(wifi_status_label, "已连接");

        if (ip_addr) {
            lv_label_set_text(ip_addr_label, ip_addr);
        }

        lv_obj_clear_flag(connection_hint_label, LV_OBJ_FLAG_HIDDEN);
    } else {
        // 连接失败
        lv_obj_add_flag(spinner, LV_OBJ_FLAG_HIDDEN);
        lv_obj_clear_flag(retry_btn, LV_OBJ_FLAG_HIDDEN);
        lv_obj_set_style_text_color(wifi_status_label, lv_color_hex(0xFF0000), 0); // 红色-连接失败
        lv_label_set_text(wifi_status_label, "连接失败");
        lv_label_set_text(ip_addr_label, "0.0.0.0");
        lv_obj_add_flag(connection_hint_label, LV_OBJ_FLAG_HIDDEN);
    }
}

// 初始化无线调试UI
static void wireless_debug_init_task(void *pvParameters)
{
    /*连接wifi*/
    if (!s_wifi_event_group) {
        wifi_init();
    }

    // 等待 WiFi 连接成功
       EventBits_t  bits = xEventGroupWaitBits(s_wifi_event_group,
                                               WIFI_CONNECTED_BIT,
                                               pdFALSE,
                                               pdFALSE,
                                               pdMS_TO_TICKS(30000));

    /*连接失败*/
    if (!(bits & WIFI_CONNECTED_BIT)) {
        update_wireless_debug_ui(false, NULL);
    } else {
        /*初始化无线调试器*/
        mdns_setup();
        set_work_status(DAP_WORK);
        DAP_Setup();

        // 获取IP地址
        const char *ip_addr = get_current_ip4();

#if (USE_TCP_NETCONN == 1)
        xTaskCreatePinnedToCore(tcp_netconn_task, "tcp_server", 4096, NULL, 14, NULL, DAP_TASK_AFFINITY);
#else // BSD style

        xTaskCreatePinnedToCoreWithCaps(tcp_server_task, "tcp_server", 4096, NULL, 14, NULL, 1, MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
#endif

        update_wireless_debug_ui(true, ip_addr);
    }
    vTaskDelete(NULL);
}

// 创建无线调试UI
lv_obj_t *create_wireless_debug_ui(void)
{
    // 创建根容器（全屏黑色背景）
    lv_obj_t *root = lv_obj_create(NULL);
    if (!root)
        return NULL;

    lv_obj_remove_style_all(root);
    lv_obj_set_size(root, LV_PCT(100), LV_PCT(100));
    uint32_t color = get_screen_color_val();
    lv_obj_set_style_bg_color(root, lv_color_hex(color), 0);
    lv_obj_set_style_bg_opa(root, LV_OPA_COVER, 0);
    lv_obj_set_style_pad_all(root, 10, 0);
    lv_obj_add_event_cb(root, event_handler, LV_EVENT_GESTURE, NULL);

    // 创建标题栏
    lv_obj_t *title_bar = lv_obj_create(root);
    lv_obj_remove_style_all(title_bar);
    lv_obj_set_size(title_bar, LV_PCT(100), 50);
    lv_obj_align(title_bar, LV_ALIGN_TOP_MID, 0, 0);
    lv_obj_set_style_bg_color(title_bar, lv_color_hex(0x2D2D2D), 0);
    lv_obj_set_style_bg_opa(title_bar, LV_OPA_COVER, 0);


    // 创建标题
    lv_obj_t *title_label = lv_label_create(title_bar);
    lv_label_set_text(title_label, "无线调试");
    lv_obj_set_style_text_font(title_label, &myFont, 0);
    lv_obj_set_style_text_color(title_label, lv_color_white(), 0);
    lv_obj_center(title_label);

    // 创建信息面板
    panel = lv_obj_create(root);
    lv_obj_remove_style_all(panel);
    lv_obj_set_size(panel, LV_PCT(95), LV_PCT(75));
    lv_obj_align(panel, LV_ALIGN_TOP_MID, 0, 60);
    lv_obj_set_style_bg_color(panel, lv_color_hex(0x1E1E1E), 0);
    lv_obj_set_style_bg_opa(panel, LV_OPA_COVER, 0);
    lv_obj_set_style_radius(panel, 12, 0);
    lv_obj_set_style_pad_all(panel, 20, 0);
    lv_obj_set_style_border_width(panel, 0, 0);

    // 使用Flex布局
    lv_obj_set_flex_flow(panel, LV_FLEX_FLOW_COLUMN);
    lv_obj_set_flex_align(panel, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
    lv_obj_set_style_pad_row(panel, 20, 0);

    // 创建状态容器
    lv_obj_t *status_container = lv_obj_create(panel);
    lv_obj_remove_style_all(status_container);
    lv_obj_set_size(status_container, LV_PCT(100), LV_SIZE_CONTENT);
    lv_obj_set_style_pad_all(status_container, 0, 0);
    // 使用网格布局排列状态信息 
    static lv_coord_t grid_col_dsc[] = { LV_GRID_FR(1), LV_GRID_FR(2), LV_GRID_TEMPLATE_LAST }; // 比例1:2
    static lv_coord_t grid_row_dsc[] = { 40, 40, LV_GRID_TEMPLATE_LAST };
    lv_obj_set_grid_dsc_array(status_container, grid_col_dsc, grid_row_dsc);

    // WiFi状态标签
    lv_obj_t *wifi_text = lv_label_create(status_container);
    lv_label_set_text(wifi_text, "WiFi状态:");
    lv_obj_set_style_text_font(wifi_text, &myFont, 0);
    lv_obj_set_style_text_color(wifi_text, lv_color_hex(0xCCCCCC), 0);
    lv_obj_set_grid_cell(wifi_text, LV_GRID_ALIGN_START, 0, 1, LV_GRID_ALIGN_CENTER, 0, 1);

    wifi_status_label = lv_label_create(status_container);
    lv_label_set_text(wifi_status_label, "连接中...");
    lv_obj_set_style_text_font(wifi_status_label, &myFont, 0);
    lv_obj_set_style_text_color(wifi_status_label, lv_color_hex(0xFFA500), 0); // 橙色-连接中
    lv_obj_set_grid_cell(wifi_status_label, LV_GRID_ALIGN_START, 1, 1, LV_GRID_ALIGN_CENTER, 0, 1);

    // IP地址标签
    lv_obj_t *ip_text = lv_label_create(status_container);
    lv_label_set_text(ip_text, "IP地址:");
    lv_obj_set_style_text_font(ip_text, &myFont, 0);
    lv_obj_set_style_text_color(ip_text, lv_color_hex(0xCCCCCC), 0);
    lv_obj_set_grid_cell(ip_text, LV_GRID_ALIGN_START, 0, 1, LV_GRID_ALIGN_CENTER, 1, 1);

    ip_addr_label = lv_label_create(status_container);
    lv_label_set_text(ip_addr_label, "获取中...");
    lv_obj_set_style_text_font(ip_addr_label, &myFont, 0);
    lv_obj_set_style_text_color(ip_addr_label, lv_color_hex(0xAAAAAA), 0);
    lv_obj_set_grid_cell(ip_addr_label, LV_GRID_ALIGN_START, 1, 1, LV_GRID_ALIGN_CENTER, 1, 1);

    // 加载动画
    spinner = lv_spinner_create(panel, 1000, 60);
    lv_obj_set_size(spinner, 50, 50);
    lv_obj_set_style_arc_color(spinner, lv_color_hex(0x0080FF), 0);

    // 连接提示
    connection_hint_label = lv_label_create(panel);
    lv_label_set_text(connection_hint_label, "请使用elaphureLink连接，输入IP地址或MdLink.local");
    lv_obj_set_style_text_font(connection_hint_label, &myFont, 0);
    lv_obj_set_style_text_color(connection_hint_label, lv_color_hex(0x888888), 0);
    lv_obj_set_style_text_align(connection_hint_label, LV_TEXT_ALIGN_CENTER, 0);
    lv_obj_set_width(connection_hint_label, LV_PCT(100));
    lv_obj_add_flag(connection_hint_label, LV_OBJ_FLAG_HIDDEN); // 初始隐藏

    // 重试按钮 (初始隐藏)
    retry_btn = lv_btn_create(panel);
    lv_obj_set_size(retry_btn, 120, 40);
    lv_obj_add_flag(retry_btn, LV_OBJ_FLAG_HIDDEN);
    lv_obj_set_style_bg_color(retry_btn, lv_color_hex(0x4CAF50), 0);
    lv_obj_set_style_radius(retry_btn, 8, 0);
    lv_obj_add_event_cb(retry_btn, retry_btn_event_handler, LV_EVENT_CLICKED, NULL);

    lv_obj_t *retry_label = lv_label_create(retry_btn);
    lv_label_set_text(retry_label, "重试连接");
    lv_obj_set_style_text_color(retry_label, lv_color_white(), 0);
    lv_obj_center(retry_label);

    /*启动连接任务*/
    xTaskCreateWithCaps(wireless_debug_init_task, "wireless_init_task", 4 * 1024, NULL, 5, NULL, MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);

    return root;
}